# -*- coding: utf-8 -*-
require "net/http"
require "mysql2"

#album_regex=/<a class="album_photo" href="(.*)><img class="album" src="(.*\.jpg)"\/><\/a>/
#album_regex=/<a class="album_photo" href="(.*)"><img class="album" src="(.*?)"\/><\/a>/
album_list_regex=/<div class="albumlst">(.*?)<br\/>/m
album_regex=/<a class="album_photo" href="(.*)"><img class="album" src="(.*?)"\/><\/a>/
album_str=/<div class="p12"><a.*?>(.*?)<\/a><\/div>/
album_descri=/<div class="albumlst_descri">(.*?)<\/div>/

photo_count=/(\d+).*?&nbsp;/
photo_update=/(\d{4}-\d{2}-\d{2})/

class MAlbum
	attr_accessor	:album_href,:album_cover,:album_str,:album_descri,:photo_count,:photo_update
end

am=MAlbum.new


mysql_client=Mysql2::Client.new(:host => "127.0.0.1", :username => "dev",:password=>"justsoso123",:database=>"xdouban")

users = mysql_client.query("select uid from user_profiles")

puts users.count



users.each do |line|

	uid = line['uid']

	puts "uid"+uid

	html=Net::HTTP.get(URI.parse("http://www.douban.com/people/#{uid}/photos"))
	html.scan(album_list_regex){ |item|
		puts "match"	
		item[0].scan(album_regex){ |album|
			am.album_href=album[0]
			am.album_cover=album[1]
	
		}



		item[0].scan(album_str){ |str|  am.album_str = mysql_client.escape(str[0]) }

		item[0].scan(album_descri) { |str| am.album_descri = mysql_client.escape(str[0]) }
		item[0].scan(photo_count) { |str| am.photo_count=str[0] }
		item[0].scan(photo_update) { |str| am.photo_update=str[0] }

		puts am.album_href	
		puts am.album_cover
		puts am.album_str
		puts am.album_descri
		puts am.photo_count
		puts am.photo_update



		sql = ("insert into user_albums (uid, href, cover, str, descri, photo_count, last_update) values ('#{uid}', '#{am.album_href}', '#{am.album_cover}', '#{am.album_str}', '#{am.album_descri}', #{am.photo_count}, '#{am.photo_update}')")
		puts sql
		mysql_client.query(sql)
	}

	sleep 10

	puts "end"


end

mysql_client.close()
